package org.sociald.wave.common;

import com.google.code.facebookapi.*;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import org.joda.time.DateTime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Timestamp;

/**
 * Created by IntelliJ IDEA.
 * User: jackie
 * Date: Dec 12, 2009
 * Time: 8:22:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class FacebookClient {
    private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
    private static final String FACEBOOK_API_KEY = "3f0d311e56d6af31a74603e142997063";
    private static final String FACEBOOK_SECRET = "26552151c07e0552c6fca69818c10e13";
    private Log logger = LogFactory.getLog(FacebookClient.class);
    private FacebookJsonRestClient client;

    public FacebookJsonRestClient getClient() {
        return client;
    }

    public void setClient(String sessionId) {
        client = new FacebookJsonRestClient(FACEBOOK_API_KEY, FACEBOOK_SECRET, sessionId);
    }

    public String getStreamByDate(String userId, DateTime endDate) throws FacebookException{
        if (client == null) {
            throw new RuntimeException("The facebook client was null");
        }
        try {
            System.out.println("ISO: "+ endDate.toDateTimeISO().toString());
            Long time = endDate.toDate().getTime();
            System.out.println(time.toString().substring(0,10));
            String queryToGetFriendName = "SELECT message,permalink,updated_time FROM stream WHERE source_id =" + userId + " and updated_time > '"+time.toString().substring(0,10)+"' LIMIT 10";
            // org.json.JSONArray friendsListArray = (org.json.JSONArray)
            Object sqlResponse = client.fql_query(queryToGetFriendName);
            if (sqlResponse instanceof JSONArray) {
                JSONArray arrayResponse = (JSONArray) sqlResponse;
                Integer itterator = 0;
                while (itterator < arrayResponse.length()) {
                    JSONObject jsonObj = (JSONObject) arrayResponse.get(itterator);
                    System.out.println(jsonObj.get("message"));
                    System.out.println(jsonObj.get("updated_time"));
                    itterator++;
                }
                //System.out.println(arrayResponse.toString());
            }
            //System.out.println("Friend Name is " + friendsListArray+ "<br>");
        }
        catch (FacebookException ex) {
            throw ex;
            
        }
        catch (JSONException jex) {
            System.out.println(">Error: Couldn't talk to JSON> " + jex);
        }
        return null;
    }
}
